// main.cpp — JingJing Day2 修正版：cin/cout，无成员函数
#include <algorithm>
#include <iostream>
#include <deque>
#include <string>
#include <utility>
#include <vector>
#include <numeric>
#include <sstream>

using std::cin;
using std::cout;
using std::deque;
using std::pair;
using std::string;
using std::vector;

constexpr size_t MAX_HIST = 4;
deque<pair<string, string>> g_hist;
vector<double> g_w;

/* ---------- 模型 ---------- */
double predict(const vector<double> &w, const vector<double> &x)
{
    return std::inner_product(w.begin(), w.end(), x.begin(), 0.0);
}

void train(const vector<vector<double>> &X, const vector<double> &y)
{
    if (X.empty())
        return;
    const size_t dim = X[0].size();
    g_w.assign(dim, 0.0);

    vector<double> x_sum(dim, 0.0);
    double y_sum = 0.0;
    for (size_t i = 0; i < X.size(); ++i)
    {
        for (size_t d = 0; d < dim; ++d)
            x_sum[d] += X[i][d];
        y_sum += y[i];
    }
    const double n = static_cast<double>(X.size());
    for (size_t d = 0; d < dim; ++d)
    {
        g_w[d] = x_sum[d] / n;
        if (g_w[d] != 0.0)
            g_w[d] = (y_sum / n) / g_w[d];
    }
}

/* ---------- 记忆 ---------- */
inline void mem_push(const string &user, const string &bot)
{
    g_hist.emplace_back(user, bot);
    if (g_hist.size() > MAX_HIST)
        g_hist.pop_front();
}

string mem_dump()
{
    string out = "[History]\n";
    for (const auto &p : g_hist)
        out += "User: " + p.first + "\nBot: " + p.second + "\n";
    out += "[Current]\n";
    return out;
}

/* ---------- 生成回复 ---------- */
string generate(const string &line)
{
    std::istringstream iss(line);
    double x0, x1;
    if (iss >> x0 >> x1)
    {
        double y = predict(g_w, {x0, x1});
        return "预测值 = " + std::to_string(y);
    }
    
    return "请给我两个数字，例如：1 2";
}

/* ---------- 主循环 ---------- */
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(nullptr);

    train({{1, 2}, {2, 3}, {3, 4}, {4, 5}}, {8, 11, 14, 17});
    cout << "[JingJing] Day2：已加载对话记忆（最多 4 轮）\n"
         << std::flush;

    string line;
    while (true)
    {
        cout << ">" << std::flush;
        if (!getline(cin, line))
            break;
        if (line == "quit")
            break;
        const string bot = generate(line);
        mem_push(line, bot);
        cout << "Bot: " << bot << '\n';
    }

    return 0;
}
